package com.gs.synedocket.util;

import static com.gs.synedocket.constant.AllConstants.TAG;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.amap.api.maps.AMapException;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.maps.offlinemap.OfflineMapProvince;
import com.gs.synedocket.R;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.EventCode;
import com.gs.synedocket.constant.HandleCode;
import com.gs.synedocket.constant.SyncStatus;
import com.gs.synedocket.db.bean.Event;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.dialog.LoadingDialogUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class MyHandler extends Handler {

    private boolean isLogin, notifyClick, isAuto, isAutoDownload, isLogout, refreshDownload, refreshListDownload, isAutoLogout, refreshLogDownload;
    private final Context context;
    private OfflineMapManager amapManager;

    public MyHandler(@NonNull Looper looper, Context context) {
        super(looper);
        this.context = context;
    }

    /**
     * 第一次登陆
     */
    public void setLogin(boolean login) {
        isLogin = login;
    }

    /**
     * 点击通知
     */
    public void setNotifyClick(boolean notifyClick) {
        this.notifyClick = notifyClick;
    }

    /**
     * 同步上传
     */
    public void setAuto(boolean auto) {
        isAuto = auto;
    }

    /**
     * 同步下载
     */
    public void setAutoDownload(boolean autoDownload) {
        isAutoDownload = autoDownload;
    }

    /**
     * 登出
     */
    public void setLogout(boolean logout) {
        isLogout = logout;
    }

    /**
     * ON HAND下拉刷新或者完成一个docket
     */
    public void setRefreshDownload(boolean refreshDownload) {
        this.refreshDownload = refreshDownload;
    }

    /**
     * Docket List下拉刷新
     */
    public void setRefreshListDownload(boolean refreshListDownload) {
        this.refreshListDownload = refreshListDownload;
    }

    /**
     * 登出时正在同步
     */
    public void setAutoLogout(boolean autoLogout) {
        isAutoLogout = autoLogout;
    }

    /**
     * Docket Log List下拉刷新
     */
    public void setRefreshLogDownload(boolean refreshLogDownload) {
        this.refreshLogDownload = refreshLogDownload;
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case HandleCode.MSG_UPLOADING:// 上傳本地數據
                if (!isAuto) {
                    showLoading(R.string.auto_upload);
                }
                break;
            case HandleCode.MSG_UPLOAD_SUCCESS:// 同步本地數據庫成功
                uploadSuccess();
                break;
            case HandleCode.MSG_UPLOAD_ERROR:// 同步本地數據庫異常
                uploadFail(msg.obj + "，" + context.getString(R.string.auto_upload_fail_log), context.getString(R.string.auto_upload_error, msg.obj));
                break;
            case HandleCode.MSG_UPLOAD_FAIL: // 同步本地數據庫失败
                uploadFail(context.getString(R.string.auto_upload_fail_log), context.getString(R.string.auto_upload_fail));
                break;
            case HandleCode.MSG_DOWNLOADING: // 同步下載
                if (!isAutoDownload) {
                    showLoading(R.string.auto_download);
                }
                break;
            case HandleCode.MSG_DOWNLOAD_SUCCESS: // 同步下載數據成功
                downloadSuccess();
                break;
            case HandleCode.MSG_DOWNLOAD_ERROR: // 同步下載數據異常
                downloadFail((String) msg.obj);
                break;
            case HandleCode.MSG_DOWNLOAD_FAIL:   // 同步下載數據失败
                downloadFail(context.getString(R.string.auto_download_fail));
                break;
            case HandleCode.MSG_DOWNLOAD_TABLE_SUCCESS:  // 同步下载数据表成功
                downloadTableSuccess();
                break;
            case HandleCode.MSG_DOWNLOAD_TABLE_FAIL: // 同步下载数据表失败
                SyncStatus.setSync(false);
//                SyncUploadUtil.getInstance().setUpload(false);
                hideLoading();
                ToastUtil.showToast(R.string.auto_download_table_fail);
                LogUtil.getInstance().insertOrReplaceData(context.getString(R.string.auto_download_table_fail));
                EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
                break;
            case HandleCode.MSG_DOWNLOAD_MAP_DONE: // 下载地图完成
                downloadMapResult((String) msg.obj);
                break;
        }
    }

    /**
     * 下载地图状态改变
     */
    private void downloadMapResult(String tip) {
        isLogin = false;
        hideLoading();
        SyncStatus.setSync(false);
//        SyncUploadUtil.getInstance().setUpload(false);
        ToastUtil.showToast(tip);
    }

    /**
     * 上传本地数据成功
     */
    private void uploadSuccess() {
        if (isAuto) {// 同步上傳結束
//            SyncStatus.setSync(false);
//            SyncUploadUtil.getInstance().setUpload(false);
            isAuto = false;
//            if (!isAutoLogout) {
            if (!isAutoLogout && !notifyClick && !refreshDownload && !refreshListDownload && !refreshLogDownload) {// 不是登出前自动同步/点击了通知时自动同步，不作操作
                SyncStatus.setSync(false);
                return;
            }
        }
        if (SyncStatus.isSync()) { // 不是同步上傳時，顯示提示
//        if (SyncUploadUtil.getInstance().isUpload()) { // 不是同步上傳時，顯示提示
            SyncStatus.setSync(false);
//            SyncUploadUtil.getInstance().setUpload(false);
            hideLoading();
            ToastUtil.showToast(R.string.auto_upload_success);
        }
        if (isLogout) {// 登出前同步上傳數據完成
            isLogout = false;
            return;
        }
        if (isAutoLogout) { // 登出時剛好在自動同步
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
//            mPresenter.logOut();
            return;
        }
        if (isLogin) { // 第一次登錄後上傳完成後繼續下載數據表
            SyncStatus.setSync(true);
//            SyncUploadUtil.getInstance().setUpload(true);
            showLoading(R.string.auto_download);
            syncSysTable();
            return;
        }
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        if (TextUtils.isEmpty(truckNo)) {
            SyncStatus.setSync(false);
//            SyncUploadUtil.getInstance().setUpload(false);
            ToastUtil.showToast(R.string.empty_truck);
            changeState();
            return;
        }
        if (refreshLogDownload)
            syncDownloadLog();
        else if (notifyClick || refreshDownload || refreshListDownload)
            syncDownload();// 點擊通知單及下拉刷新時繼續下載OnHandList數據
    }

    /**
     * 同步下載Docket OnHandList数据
     */
    private void syncDownload() {
        new Thread(() -> {
            SyncDownloadUtil.getInstance().setOnSyncListener(this::sendMsg);
            SyncDownloadUtil.getInstance().downloadOnHandList();
        }).start();
    }

    /**
     * 同步下載Docket deliveryLogList数据
     */
    private void syncDownloadLog() {
        new Thread(() -> {
            SyncDownloadUtil.getInstance().setOnSyncListener(this::sendMsg);
            SyncDownloadUtil.getInstance().downloadLogList();
        }).start();
    }

    private void sendMsg(int status, String msg) {
        Message message = Message.obtain();
        message.what = status;
        message.obj = msg;
        sendMessage(message);
    }

    /**
     * 上传本地数据失败
     */
    private void uploadFail(String logoutMsg, String msg) {
        if (isAuto) {// 自動同步時失敗不作處理
            isAuto = false;
            if (!isAutoLogout) {
                return;
            }
        }
        hideLoading();
        if (isLogin) {
            ToastUtil.showToast(logoutMsg);
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
            return;
        }
        ToastUtil.showToast(msg);
        if (isLogout) {// 登出前同步上傳數據
            isLogout = false;
            return;
        }
        if (isAutoLogout) {
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
            return;
        }
        changeState();
    }

    /**
     * 下載數據成功
     */
    private void downloadSuccess() {
        if (refreshDownload) {
            if (TextUtils.isEmpty(DocketUtil.getInstance().getDocketId())) {
                EventBus.getDefault().post(new Event(EventCode.EVENT_DOWNLOAD_SUCCESS));
            }
            refreshDownload = false;
        } else if (refreshListDownload) {
            refreshListDownload = false;
            EventBus.getDefault().post(new Event(EventCode.EVENT_LIST_DOWNLOAD_SUCCESS));
        } else if (refreshLogDownload) {
            refreshLogDownload = false;
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOG_DOWNLOAD_SUCCESS));
        }
        if (isAutoDownload) {
            isAutoDownload = false;
            if (!isAutoLogout) {
                return;
            }
        }
        hideLoading();
        ToastUtil.showToast(R.string.auto_download_success);
        if (isAutoLogout) { // 登出時剛好在自動同步
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
            return;
        }
        if (notifyClick) {
            notifyClick = false;
            EventBus.getDefault().post(new Event(EventCode.EVENT_SHOW_FRAGMENT));
        }
    }

    /**
     * 下載數據失敗
     */
    private void downloadFail(String msg) {
        refreshDownload = false;
        refreshListDownload = false;
        refreshLogDownload = false;
        if (isAutoDownload) {
            isAutoDownload = false;
            if (!isAutoLogout) {
                return;
            }
        }
        hideLoading();
        ToastUtil.showToast(msg);
        if (isAutoLogout) {
            EventBus.getDefault().post(new Event(EventCode.EVENT_LOGOUT));
            return;
        }
        if (notifyClick) {
            notifyClick = false;
            EventBus.getDefault().post(new Event(EventCode.EVENT_SHOW_FRAGMENT));
        }
    }

    /**
     * 下载全部数据表
     */
    private void syncSysTable() {
        new Thread(() -> {
            SyncTableUtil.getInstance().setOnSyncListener(this::sendMsg);
            SyncTableUtil.getInstance().download();
        }).start();
    }

    /**
     * 下载数据表成功
     */
    private void downloadTableSuccess() {
        ToastUtil.showToast(R.string.download_table_success);
        if (isLogin) {
            showLoading(R.string.download_map);
//            ThreadManager.getInstance().execute(() -> {
            DBApi.getInstance().addLogoutMenu();
            EventBus.getDefault().post(new Event(EventCode.EVENT_SHOW_MENU));
            downloadMap();
//            });
        } else {// 没有在登录后下载成功table，重新下载
            SyncStatus.setSync(false);
//            SyncUploadUtil.getInstance().setUpload(false);
            hideLoading();
            DBApi.getInstance().addLogoutMenu();
            EventBus.getDefault().post(new Event(EventCode.EVENT_SHOW_MENU));
        }
    }

    private void changeState() {
        if (notifyClick) {
            notifyClick = false;
            EventBus.getDefault().post(new Event(EventCode.EVENT_SHOW_FRAGMENT));
        }
        refreshDownload = false;
        refreshListDownload = false;
        refreshLogDownload = false;
    }

    /**
     * 下载地图
     */
    private void downloadMap() {
        try {
            amapManager = new OfflineMapManager(context, new MyOfflineMapDownloadListener());
            ArrayList<OfflineMapProvince> provinceList = amapManager.getDownloadOfflineMapProvinceList();
            if (!provinceList.isEmpty()) {
                for (OfflineMapProvince province : provinceList) {
                    if (province.getProvinceName().equals("香港特别行政区")) {
                        amapManager.updateOfflineMapProvinceByName("香港特别行政区");
                        return;
                    }
                }
            }
            amapManager.downloadByProvinceName("香港特别行政区");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyOfflineMapDownloadListener implements OfflineMapManager.OfflineMapDownloadListener {

        @Override
        public void onDownload(int i, int i1, String s) {
            Log.i(TAG, "state:" + i);
            if (isLogin) {
                switch (i) {
                    case 4:
                        sendMsg(HandleCode.MSG_DOWNLOAD_MAP_DONE, context.getString(R.string.download_map_success));
                        break;
                    case 102:
                        sendMsg(HandleCode.MSG_DOWNLOAD_MAP_DONE, context.getString(R.string.download_map_key));
                        break;
                    case 101:
                    case 103:
                        sendMsg(HandleCode.MSG_DOWNLOAD_MAP_DONE, context.getString(R.string.download_map_error));
                        break;
                }
            }
        }

        @Override
        public void onCheckUpdate(boolean b, String s) {
            if (b) {
                try {
                    amapManager.downloadByCityName("香港特别行政区");
                } catch (AMapException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onRemove(boolean b, String s, String s1) {

        }
    }


    private void showLoading(int tip) {
        LoadingDialogUtils.getInstance().showLoading(context, context.getString(tip));
        LoadingDialogUtils.getInstance().setCancelable(false);
    }

    private void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }
}
